package server2;

import io.Packet;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * 
 * 閹恒儱鍩岀�广垺鍩涚粩顖涙殶閹诡喗妞傞惃鍕煒閸栧懏鏌熷锟�
 */
public class MinaDecoder extends CumulativeProtocolDecoder {

	@Override
	protected boolean doDecode(IoSession ioSession, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		
		int remain = in.remaining();
		// 濡傛灉娌℃湁鎺ユ敹瀹孒eader閮ㄥ垎锛�4瀛楄妭锛夛紝鐩存帴杩斿洖false 
        if (remain < 2) {  
            return false;  
        } else{
  
        	byte[] data = in.array();
            // 鏍囪寮�濮嬩綅缃紝濡傛灉涓�鏉℃秷鎭病浼犺緭瀹屾垚鍒欒繑鍥炲埌杩欎釜浣嶇疆  
            in.mark();
       
            // 璇诲彇header閮ㄥ垎锛岃幏鍙朾ody闀垮害  
           // int bodyLength = in.getInt();  
           // int bodyLength = CommonTool.byte2int(new byte[]{data[0],data[1],data[2],data[3]});
            int bodyLength =  (int)(((int)data[0] << 8) | ((int)data[1]));
         
            // 濡傛灉body娌℃湁鎺ユ敹瀹屾暣锛岀洿鎺ヨ繑鍥瀎alse  
            if (remain < bodyLength) {  
                in.reset();  
                return false;  
            } 
            else 
            {  
            	int val = data[3];
            	if(val < 0) val += 256;
            	
            	int head = (int)(((int)data[2] << 8) | val);
 
            	//int head = CommonTool.byte2int(new byte[]{data[4],data[5],data[6],data[7]});
            	
            	in.position(in.position() + 4);
                byte[] bodyBytes = new byte[bodyLength - 4];
                in.get(bodyBytes); // 璇诲彇body閮ㄥ垎
            	
            	IoBuffer buf  = IoBuffer.wrap(bodyBytes);
            	Packet packet = new Packet((short)head,(byte)3,buf);
            	
                out.write(packet); // 瑙ｆ瀽鍑轰竴鏉℃秷鎭� 
                
                return true;  
            }  
        }
	}
}
